//重复可以用子集树，不要重复使用排列树
//算术运算符+、-、*、/
//有5个数，7 2 2 12 3。算出125
public class MQuestion {
    //定义全局变量
    static int[] nums = {7, 2, 2, 12, 3};
    static char[] operator;//用来存放运算符
    static int finalNum = 125;

    public static void permit(int[] nums) {
        //初始化
        //此处的4并不代表有4个操作数，而是5个数之间只能放4个操作数
        operator = new char[nums.length - 1];

    }

    //交换
    public static void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }

    // (2 + 1) * 3 = 9 ; 9
    // 2 + 1 = 3
    // 3 * 3 = 9

    public static void printfResult() {
        int x1 = nums[0];
        int x2 = x1;//x2的作用是将前一个值的结果保存起来
        for (int i = 0; i < nums.length - 1; i++) {
            x2 = x1;
            switch (operator[i]) {
                case '+':
                    x1 = x2 + nums[i + 1];
                    break;
                case '-':
                    x1 = x2 + nums[i + 1];
                    break;
                case '*':
                    x1 = x2 * nums[i + 1];
                    break;
                case '/':
                    x1 = x2 / nums[i + 1];
                    break;
            }
            System.out.println(x2 + "" + operator[i]
                    + nums[i + 1] + '=' + x1);
        }
    }

    public static void output() {
        int x = nums[0];
        for (int i = 0; i < nums.length - 1; i++) {
            switch (operator[i]) {
                case '+':
                    x += nums[i + 1];
                    break;
                case '-':
                    x -= nums[i + 1];
                    break;
                case '*':
                    x *= nums[i + 1];
                    break;
                case '/':
                    x /= nums[i + 1];
                    break;
            }
        }
        if (x == finalNum) {

            System.exit(-1);
        }
    }

    //对运算符进行求子集
    public static void backTrapTow(int now) {
        //
        if (now == nums.length - 1) {
            output();
        } else {
            operator[now] = '+';
            backTrapTow(now + 1);
            operator[now] = '-';
            backTrapTow(now + 1);
            operator[now] = '*';
            backTrapTow(now + 1);
            operator[now] = '/';
            backTrapTow(now + 1);
        }
    }

    //对5个数求排列
    public static void backTrapOne(int now) {
        if (now == nums.length) {
            //对运算符进行求子集
            backTrapTow(0);
        } else {
            for (int i = now; i < nums.length; i++) {
                swap(nums, i, now);
                backTrapOne(now + 1);
                //恢复现场
                swap(nums, i, now);
            }
        }
    }
}
